#define RESOLUTION iResolution.xy// 分辨率
#define RAYMARCH_SAMPLES 128// 采样次数（即步进次数）
#define RAYMARCH_MULTISAMPLE 1// 多重采样次数（即抗锯齿次数）
#define RAYMARCH_BACKGROUND vec3(0.)// 背景色
#define RAYMARCH_CAMERA_FOV 2.// 相机视场角

#define COLOR_1 vec3(.757,.765,.729)
#define COLOR_2 vec3(.553,.239,.227)
#define COLOR_3 vec3(.278,.039,.063)
#define COLOR_4 vec3(.001,.001,.001)
#define COLOR_5 vec3(.745,.596,.341)
#define COLOR_6 vec3(.302,.082,.098)

#include "/node_modules/lygia/space/ratio.glsl";

#define RAYMARCH_MATERIAL_FNC raymarchCustomMaterial
vec3 raymarchCustomMaterial(vec3 ray,vec3 pos,vec3 nor,vec3 map);

#include "/node_modules/lygia/lighting/raymarch.glsl";
#include "/node_modules/lygia/sdf.glsl";

vec3 raymarchCustomMaterial(vec3 ray, vec3 pos, vec3 nor, vec3 map){
    vec3 col = vec3(0.);
    
    col += map * .2;

    vec3 lightPos = vec3(10.);
    vec3 lightDir = normalize(lightPos - pos);
    float diff = max(dot(lightDir, nor), 0.);
    col += map * diff;

    vec3 reflectDir = reflect(-lightDir, nor);
    vec3 viewDir = normalize(-ray);
    vec3 halfVec = normalize(lightDir + viewDir);
    float spec = pow(max(dot(nor, halfVec), 0.), 32.);
    col += map * spec;

    return col;
}

vec4 jumpyDumpty(vec3 p, vec4 res){
    vec3 p1 = p;
    float head = sphereSDF(p1, .69);

    // 加一个方块
    head = opIntersection(head, boxSDF(p1 - vec3(0., 1.3, 0.), vec3(1.)));
    
    res = opUnion(res, vec4(COLOR_1, head));

    // ear
    vec3 p2 = p;
    p2.x = abs(p2.x);
    float ear = ellipsoidSDF(rotate(p2 - vec3(.45, .7, 0.), -PI / 3., vec3(0., 0., 1.)), vec3(.1, .25, .1));
    res = opUnion(res, vec4(COLOR_1, ear), .025);

    // body
    vec3 p3 = p;
    p3.y /= .8;
    float body = coneSDF(p3 - vec3(0., -.6, 0.), .75, .5, 1.);

    // 切除一部分
    body = opIntersection(body, boxSDF(p3 - vec3(0., -1., 0.), vec3(1.)));

    body *= .8;
    res = opUnion(res, vec4(COLOR_2, body));

    return res;
}

vec4 raymarchMap(vec3 p){
    vec4 res = vec4(1.);
    //res = opUnion(res, vec4(vec3(.875, .286, .333), sphereSDF(p - vec3(0., 0., -2.), 1.)));

    vec3 p1 = p;
    res = jumpyDumpty(p1, res);
    return res;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord){
    vec2 uv = fragCoord / iResolution.xy;
    uv = ratio(uv, iResolution.xy);
    vec3 col = vec3(0.);
    vec3 camera = vec3(0., 0., 30.);
    col = raymarch(camera, uv).rgb;
    fragColor = vec4(col, 1.);
}